package cn.lupin.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Map;

import cn.lupin.pojo.PublisherVideo;
import cn.lupin.pojo.Users;
import cn.lupin.pojo.UsersReport;
import cn.lupin.pojo.UsersVO;
import cn.lupin.service.UserService;
import cn.lupin.utils.LaughJSONResult;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

@RestController
@Api(value = "用户相关业务的接口", tags = {"用户相关业务的controller"})
@RequestMapping("/user")
public class UserController extends BasicController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "用户上传头像", notes = "用户上传头像的接口")
    @ApiImplicitParam(name = "userId", value = "用户id", required = true,
            dataType = "string", paramType = "query")
    @PostMapping("/uploadFace")
    public LaughJSONResult uploadFace(String userId, @RequestParam("file") MultipartFile[] files) throws Exception {

        if (StringUtils.isBlank(userId)) {
            return LaughJSONResult.errorMsg("用户id不能为空...");
        }
        // 文件保存的命名空间
        String fileSpace = FILE_SPACE;
        // 保存到数据库中的相对路径
        String uploadPathDB = "/" + userId + "/face";
        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;
        try {
            if (files != null && files.length > 0) {
                String fileName = files[0].getOriginalFilename();
                if (StringUtils.isNotBlank(fileName)) {
                    // 设置数据库保存的路径
                    uploadPathDB = uploadPathDB + "/" + fileName;
                    // 文件上传的最终保存路径
                    String finalFacePath = fileSpace + uploadPathDB;
                    File outFile = new File(finalFacePath);
                    if (outFile.getParentFile() != null || !outFile.getParentFile().isDirectory()) {
                        // 创建父文件夹
                        outFile.getParentFile().mkdirs();
                    }
                    fileOutputStream = new FileOutputStream(outFile);
                    inputStream = files[0].getInputStream();
                    IOUtils.copy(inputStream, fileOutputStream);
                }
            } else {
                return LaughJSONResult.errorMsg("上传出错...");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return LaughJSONResult.errorMsg("上传出错...");
        } finally {
            if (fileOutputStream != null) {
                fileOutputStream.flush();
                fileOutputStream.close();
            }
        }
        Users user = new Users();
        user.setId(userId);
        user.setFaceImage(uploadPathDB);
        userService.updateUserInfo(user);
        return LaughJSONResult.ok(uploadPathDB);
    }

    @ApiOperation(value = "查询用户信息", notes = "查询用户信息的接口")
    @ApiImplicitParam(name = "userId", value = "用户id", required = true,
            dataType = "string", paramType = "query")
    @PostMapping("/query")
    public LaughJSONResult query(String userId, String fanId) throws Exception {

        if (StringUtils.isBlank(userId)) {
            return LaughJSONResult.errorMsg("用户id不能为空...");
        }
        UsersVO userVO = new UsersVO();
        Users user = userService.queryUserInfo(userId);
        user.setPassword("");
        userVO.setUser(user);
        boolean ifFollow = userService.queryIfFollow(userId, fanId);
        userVO.setFollow(ifFollow);
        return LaughJSONResult.ok(userVO);
    }

    @ApiOperation(value = "查询用户信息", notes = "查询用户信息的接口")
    @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "string", paramType = "query")
    @GetMapping("/update/nickname")
    public LaughJSONResult updateNickName(String userId, String nickname) throws Exception {
        if (StringUtils.isBlank(userId)) {
            return LaughJSONResult.errorMsg("用户id不能为空...");
        }
        Users user = new Users();
        user.setId(userId);
        user.setNickname(nickname);
        userService.updateUserInfo(user);
        return LaughJSONResult.ok();
    }


    @PostMapping("/queryPublisher")
    public LaughJSONResult queryPublisher(String loginUserId, String videoId,
                                          String publishUserId) throws Exception {

        if (StringUtils.isBlank(publishUserId)) {
            return LaughJSONResult.errorMsg("");
        }
        PublisherVideo pv = new PublisherVideo();
        // 1. 查询视频发布者的信息
        Users userInfo = userService.queryUserInfo(publishUserId);
        UsersVO usersVO = new UsersVO();
        usersVO.setUser(userInfo);
        pv.setPublisher(usersVO);
        // 2.查询当前视频的点赞数，收藏数，评论数
        Map<String, Long> counts = userService.getUserVideoCounts(publishUserId, videoId);
        pv.setLikeCounts(counts.get("likeCounts"));
        pv.setCollectCounts(counts.get("collectCounts"));
        pv.setCommentCounts(counts.get("commentCounts"));
        //设置默认值
        pv.setUserLikeVideo(false);
        pv.setUserCollectVideo(false);
        pv.setPublisherFan(false);
        if (loginUserId != null) {
            // 3. 查询当前登录者和视频的点赞关系
            boolean userLikeVideo = userService.isUserLikeVideo(loginUserId, videoId);
            pv.setUserLikeVideo(userLikeVideo);
            // 4.查询当前登录者和视频的收藏关系
            boolean userCollectVideo = userService.isUserCollectVideo(loginUserId, videoId);
            pv.setUserCollectVideo(userCollectVideo);
            //5.查询当前登录者和视频发布者的关系
            boolean publisherFan = userService.queryIfFollow(publishUserId, loginUserId);
            pv.setPublisherFan(publisherFan);
        }
        return LaughJSONResult.ok(pv);
    }

    @PostMapping("/beyourfans")
    public LaughJSONResult beyourfans(String userId, String fanId) throws Exception {

        if (StringUtils.isBlank(userId) || StringUtils.isBlank(fanId)) {
            return LaughJSONResult.errorMsg("");
        }
        userService.saveUserFanRelation(userId, fanId);
        return LaughJSONResult.ok("关注成功...");
    }

    @PostMapping("/dontbeyourfans")
    public LaughJSONResult dontbeyourfans(String userId, String fanId) throws Exception {

        if (StringUtils.isBlank(userId) || StringUtils.isBlank(fanId)) {
            return LaughJSONResult.errorMsg("");
        }
        userService.deleteUserFanRelation(userId, fanId);
        return LaughJSONResult.ok("取消关注成功...");
    }

    @PostMapping("/reportUser")
    public LaughJSONResult reportUser(@RequestBody UsersReport usersReport) throws Exception {
        // 保存举报信息
        userService.reportUser(usersReport);
        return LaughJSONResult.errorMsg("举报成功...");
    }
}
